/*
 * Copyright 2010 Eligio Colutta
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * http://www.apache.org/licenses/LICENSE-2.0 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 */
package com.google.code.p2pxmppclient.notifyserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.Socket;


/**
 * 
 * @author eliosh
 * @version $Rev$
 * @lastautorcommit $Author$
 * @lastdatecommit $Date$
 */
public class NotifyClient {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		/*
		 * 0 port
		 * 1 message
		 */
		if(args.length<2){
			System.err.println("ERROR: <port> <message>");
			System.exit(1);
		}
		
		String portStr = args[0];
		int port = Integer.parseInt(portStr);
		String message = getMessage(args);
		
        //
        // Create a connection to the server socket on the server application
        //
        InetAddress host = Inet4Address.getByName("localhost");
        Socket socket = new Socket(host.getCanonicalHostName(), port);

        //
        // Send a message to the client application
        //
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out.println(message + "\r\n");
        
        //
        // Read and display the response message sent by server application
        
        String result = in.readLine();
        System.out.println("Server Message: " + result);

        in.close();
        out.close();
        socket.close();
	}

	private static String getMessage(String[] words){
		StringBuilder sb = new StringBuilder();
		for(int k=1; k<words.length; k++){
			sb.append(words[k]).append(" ");
		}
		return sb.toString();
	}
}
